import json
from json import JSONDecodeError
from logging import Logger, getLogger

from django.forms import Form
from django.http import HttpRequest

from common.errors import InvalidParameter

default_logger = getLogger(__name__)


def get_request_data(request: HttpRequest, logger: Logger = default_logger):
    """获取request中的参数"""
    data = {}
    if request.method == "POST":
        try:
            data = json.loads(request.body)
        except (JSONDecodeError, TypeError):
            logger.error(
                json.dumps(
                    {
                        "error": "request_body无法被反序列化",
                        "request_body": str(request.body),
                    },
                    ensure_ascii=False,
                )
            )
            raise InvalidParameter("参数错误")
        logger.info(json.dumps(data, ensure_ascii=False))
        if (data_type := type(data)) != dict:
            logger.error(
                json.dumps(
                    {
                        "error": "request_body反序列化后类型不为dict",
                        "request_body": data,
                        "type_after_deserialized": str(data_type),
                    },
                    ensure_ascii=False,
                )
            )
            raise InvalidParameter("参数错误")
    elif request.method == "GET":
        data = request.GET.dict()

    return data


def request_parameter_check(
    data: dict, form_class: Form, logger: Logger = default_logger
) -> Form:
    """校验参数是否合法"""
    form = form_class(data)
    if not form.is_valid():
        logger.error(json.dumps({"error": form.errors}, ensure_ascii=False))
        raise InvalidParameter("参数错误")
    return form
